import requests
import json
import random
import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend

from .models import MyUser


def get_user_token(user_data):
    """
    oauth生成token
    :param user_data:
    :return:
    """

    url = settings.REQUEST_URL

    my_dict = {
        "grant_type": settings.GRANT_TYPE,
        "client_id": settings.CLIENT_ID,
        "username": user_data.get("email"),
        "password": user_data.get("password")
    }

    try:
        r = requests.post(url, data=my_dict)
    except Exception as e:

        raise e

    data = r.content.decode()

    d = json.loads(data)

    token = d.get("access_token", None)

    return token


def create_password():
    constant_sign = '1234567890abcdefghijklmnopqrstuvwxyz'
    sign = ''.join(random.sample(constant_sign, k=8))
    return sign


def get_user_by_account(account):
    """
    根据帐号获取user对象
    account: 账号，可以是用户名，也可以是手机号
    return: User对象 或者 None
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = MyUser.objects.get(phone=account)
        else:
            user = MyUser.objects.get(email=account)
    except MyUser.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    '''o/token => email&phone'''

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user
